//
//  UINestedScrollView2VC.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2022/10/26.
//

import Foundation
import UIKit
import MJRefresh
import RxSwift

final class UINestedScrollView2VC: UIViewController {
  private var parentScrollEnabled: Bool = true
  private var childScrollEnabled: Bool = false
  
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    
    initView()
    initData()
  }
  
  private func initView() {
    view.addSubview(scrollView)
    scrollView.snp.makeConstraints { make in
      make.top.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide)
    }
    
    scrollView.addSubview(headerView)
    headerView.snp.makeConstraints { make in
      make.width.equalToSuperview().inset(16)
      make.height.equalTo(200)
      make.top.equalToSuperview()
      make.leading.trailing.equalToSuperview().inset(16)
    }
    
    scrollView.addSubview(segmentedControl)
    segmentedControl.snp.makeConstraints { make in
      make.width.equalToSuperview().inset(16)
      make.height.equalTo(38)
      make.top.equalTo(headerView.snp.bottom).offset(16)
      make.leading.trailing.equalToSuperview().inset(16)
    }
    
    scrollView.addSubview(containerView)
    containerView.snp.makeConstraints { make in
      make.width.equalToSuperview().inset(16)
      make.height.equalToSuperview().offset(-70)
      make.top.equalTo(segmentedControl.snp.bottom).offset(16)
      make.leading.trailing.equalToSuperview().inset(16)
      make.bottom.equalToSuperview()
    }
  }
  
  private func initData() {
    tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
      self?.delay(seconds: 1) {
        self?.tableView.mj_header?.endRefreshing()
      }
    })
    
    tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { [weak self] in
      self?.delay(seconds: 1, closure: {
        self?.tableView.mj_footer?.endRefreshing {
          print("mj_footer endRefreshing")
        }
      })
    })
    
    scrollView.mj_header = MJRefreshNormalHeader(refreshingBlock: { [weak self] in
      self?.delay(seconds: 1) {
        self?.scrollView.mj_header?.endRefreshing()
      }
    })
    
//    scrollView.bounces = false
    tableView.contentOffset.y = 1
  }
  
  private func delay(seconds: Int, closure: @escaping ()->()) {
    let time = DispatchTime.now() + .seconds(seconds)
    DispatchQueue.main.asyncAfter(deadline: time) {
      print("🕑")
      closure()
    }
  }
  
  private lazy var scrollView: NestedScrollView2 = {
    let scrollView = NestedScrollView2()
    scrollView.delegate = self
    return scrollView
  }()
  
  private lazy var contentView: UIView = {
    let view = UIView()
    return view
  }()
  
  private lazy var headerView: UIView = {
    let view = UILabel()
    view.text = "Header"
    view.textColor = .white
    view.backgroundColor = .red.withAlphaComponent(0.5)
    return view
  }()
  
  private lazy var segmentedControl: UIView = {
    let view = UIView()
    view.backgroundColor = .green.withAlphaComponent(0.5)
    return view
  }()
  
  private lazy var containerView: UIView = {
    let view = UIView()
    view.backgroundColor = .blue.withAlphaComponent(0.5)
    
    view.addSubview(tableView)
    tableView.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
    return view
  }()
  
  private lazy var tableView: UITableView = {
    let tableView = UITableView(frame: .zero, style: .plain)
    tableView.backgroundColor = .clear
    tableView.dataSource = self
    (tableView as UIScrollView).delegate = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
    return tableView
  }()
  
  let tableCount = 20
}

extension UINestedScrollView2VC: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableCount
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
    cell.textLabel?.text = "row: \(indexPath.row)"
    cell.textLabel?.textColor = .black
    cell.backgroundColor = .clear
    return cell
  }
}

/**
 两种种状态
 1. 展开状态，Header显示
    - 向下滑动，ScrollView 响应；
    - 向上滑动，ScrollView 响应；状态 1 ~ 2
 2. 收起状态，Header收起
    - 向上滑动，TableView 响应；
    - 向下滑动，ScrollView 响应；状态 2 ~ 1
  */
extension UINestedScrollView2VC: UIScrollViewDelegate {
  func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == self.scrollView {
      let topOffset = headerView.frame.height
      // 无效高度
      if topOffset <= 0 { return }
      print("scrollView.contentOffset1:", scrollView.contentOffset)
      if self.parentScrollEnabled == false {
        scrollView.contentOffset = CGPoint(x: 0, y: topOffset)
      } else if scrollView.contentOffset.y >= topOffset {
        scrollView.contentOffset = CGPoint(x: 0, y: topOffset)
        self.parentScrollEnabled = false
        self.childScrollEnabled = true
      }
    } else if scrollView == self.tableView {
      print("scrollView.contentOffset2:", scrollView.contentOffset)
      if childScrollEnabled == false {
        scrollView.contentOffset = CGPoint.zero
      } else if scrollView.contentOffset.y <= 0 {
        childScrollEnabled = false
        parentScrollEnabled = true
      }
    }
  }
}

private class NestedScrollView2: UIScrollView { }

extension NestedScrollView2: UIGestureRecognizerDelegate {
  /// 实现手势穿透的关键代码
  ///
  /// 返回 true 允许两者同时识别。默认实现返回 false（默认情况下不能同时识别两个手势）
  public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
  }
}
